﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Xml;
using bmapi.HelperClass;
using bmapi.Models.DataEntity;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using static bmapi.HelperClass.AssistFun;

namespace bmapi.Controllers
{
    public class CADApplyController : CADController
    {
        [HttpGet, Route("cadApply/ReDownLoad")]
        public string ReDownLoad()
        {
            WriteLog("cadApply/ReDownLoad", "无参", true);
            //这个接口用来解决重新下载问题 
            User user = GetUserByLoginID(GetCrrentIDByToken());
            if (user == null)
                return ReturnPCList(null);
            else
            {

                if (user.code == 35 || user.code2 == 35 || user.code3 == 35)
                {
                    string sql = "select pod_id as PodId ,Pod_tb.Pod,Pod_tb.time as Time, PC_tb.pc_id as OrderId, PC_tb.path as PcName,model_id as ModelId from Pod_tb join PC_tb on Pod_tb.order_id=PC_tb.pc_id where user_id=@loginid and state=0 order by Pod_tb.time desc";
                    SQLCommand sc = new SQLCommand(sql, "@loginid", user.login_id);
                    DataTable dt = sc.ExecuteScalars();
                    if (dt == null)
                        return ReturnPodList(null);
                    else
                    {
                        List<PidOid> pod = DataTableToList<PidOid>(dt);
                        WriteDebug("ReDownLoad2", "特体数:" + pod.Count);
                        return ReturnPodList(pod);
                    }
                }
                else
                {
                    SQLCommand sc = new SQLCommand("select PC_tb.* from PC_tb where station=@loginid and download=1 and (bind_id=0 or bind_id=pc_id)", "@loginid", user.login_id);
                    DataTable dt = sc.ExecuteScalars();
                    if (dt == null)
                        return ReturnPCList(null);
                    else
                    {
                        List<PC> pc = DataTableToList<PC>(dt);
                        return ReturnPCList(pc);
                    }
                }
            }
        }

        protected string ReturnPodList(List<PidOid> pod)
        {
            WriteDebug("ReturnPodList1", "进入返回重新下载的特体 ");
            XmlDocument doc = new XmlDocument();

            XmlNode root = doc.CreateElement("list");
            doc.AppendChild(root);

            XmlElement p = doc.CreateElement("status");
            p.InnerText = "200";
            root.AppendChild(p);

            p = doc.CreateElement("tip");
            root.AppendChild(p);

            XmlNode list = doc.CreateElement("taskList");
            root.AppendChild(list);

            if (pod == null)
            {
                p.InnerText = "没有";
            }
            else
            {
                p.InnerText = "OK";
                int i = 0;
                foreach (PidOid one in pod)
                {
                    XmlNode task = doc.CreateElement("task");
                    list.AppendChild(task);

                    p = doc.CreateElement("id");
                    p.InnerText = one.OrderId.ToString();
                    task.AppendChild(p);

                    p = doc.CreateElement("name");
                    p.InnerText = one.PcName;
                    task.AppendChild(p);

                    p = doc.CreateElement("pod");
                    p.InnerText = one.Pod.ToString();
                    task.AppendChild(p);

                    p = doc.CreateElement("time");
                    p.InnerText = one.Time.ToString("yyyy-MM-dd HH:mm");
                    task.AppendChild(p);
                    WriteDebug("ReturnPodList", "pod" + (i += 1) + "：" + one.Pod);
                }
            }
            WriteDebug("ReturnPodList", "返回xml");
            return ConvertXmlToString(doc);
        }
        protected string ReturnPCList(List<PC> pc)
        {

            XmlDocument doc = new XmlDocument();

            XmlNode root = doc.CreateElement("list");
            doc.AppendChild(root);

            XmlElement p = doc.CreateElement("status");
            p.InnerText = "200";
            root.AppendChild(p);

            p = doc.CreateElement("tip");
            root.AppendChild(p);

            XmlNode list = doc.CreateElement("taskList");
            root.AppendChild(list);

            if (pc == null)
            {
                p.InnerText = "没有";
            }
            else
            {
                p.InnerText = "OK";

                foreach (PC one in pc)
                {
                    XmlNode task = doc.CreateElement("task");
                    list.AppendChild(task);

                    p = doc.CreateElement("id");
                    p.InnerText = one.pc_id.ToString();
                    task.AppendChild(p);

                    p = doc.CreateElement("name");
                    p.InnerText = one.path;
                    task.AppendChild(p);

                    p = doc.CreateElement("process");
                    p.InnerText = one.step.ToString();
                    task.AppendChild(p);

                    p = doc.CreateElement("time");
                    p.InnerText = GetPcTime(one.pc_id).ToString("yyyy-MM-dd HH:mm");
                    task.AppendChild(p);
                }
            }

            return ConvertXmlToString(doc);
        }

        private DateTime GetPcTime(int pc_id)
        {
            User user = GetUserByLoginID(GetCrrentIDByToken());
            string sql = "select time from Task_tb where id=@pcid and user_id=@userid and code=@code";
            SQLCommand sc = new SQLCommand(sql);
            sc.Add("@pcid", pc_id);
            sc.Add("@userid", user.login_id);
            sc.Add("@code", user.code);
            DateTime time = DateTime.Now;
            string tomes = sc.ExecuteScalar();
            if (tomes != null)
                time = Convert.ToDateTime(tomes);
            return time;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="id">流程id</param>
        /// <param name="process">工序编号</param>
        /// <param name="name">流程名</param>
        /// <param name="pod">pod文件名</param>
        /// <returns></returns>
        protected string ReturnOK(int id, int process, string name, int pod = 0)
        {
            WriteDebug("ReturnOK", "流程-" + id + "工序编号-" + process + "流程名-" + name + "pod文件名-" + pod);
            XmlDocument doc = new XmlDocument();

            XmlNode root = doc.CreateElement("task");
            doc.AppendChild(root);

            XmlElement p = doc.CreateElement("status");
            p.InnerText = "200";
            root.AppendChild(p);

            p = doc.CreateElement("tip");
            p.InnerText = "OK";
            root.AppendChild(p);

            p = doc.CreateElement("id");
            p.InnerText = id.ToString();
            root.AppendChild(p);

            string sql = "select Model_tb.name from Model_tb join PC_tb on Model_tb.id=PC_tb.model_id where pc_id=@pcid";
            SQLCommand sc = new SQLCommand(sql, "@pcid", id);
            string modelName = sc.ExecuteScalar();
            if (modelName == null)
                modelName = "";
            p = doc.CreateElement("model");
            p.InnerText = modelName;
            root.AppendChild(p);

            p = doc.CreateElement("name");
            p.InnerText = name;
            root.AppendChild(p);

            p = doc.CreateElement("process");
            p.InnerText = process.ToString();
            root.AppendChild(p);

            p = doc.CreateElement("pod");
            p.InnerText = pod.ToString();
            root.AppendChild(p);

            return ConvertXmlToString(doc);
        }
        /// <summary>
        /// 获得一个流程，分给他
        /// </summary>  
        /// <param name="u"></param>
        /// <returns></returns>
        protected PC LockTask(User u, bool isOrder)
        {
            string sql = "";
            SQLCommand sc = null;
            try
            {
                //sql = "select PC_tb.* from PC_tb where station=@loginid and download=0";
                sql = "select PC_tb.* from PC_tb join Order_tb on pc_id=Order_tb.id where station=@loginid and (step=@code1 or step=@code2 or step=@code3) and download=0 order by Order_tb.rank desc,Order_tb.finish_time asc";
                sc = new SQLCommand(sql);
                sc.Add("@loginid", u.login_id);
                sc.Add("@code1", u.code == 35 ? 0 : u.code); //申请特体以外的打版任务 
                sc.Add("@code2", u.code2 == 35 ? 0 : u.code2);
                sc.Add("@code3", u.code3 == 35 ? 0 : u.code3);
                DataTable dt = sc.ExecuteScalars();
                if (dt != null)
                {
                    List<PC> pcList = DataTableToList<PC>(dt);
                    foreach (PC pc in pcList)
                    {
                        pc.maxStep = GetMax(pc.maxStep, pc.step);
                        pc.grouping = GetMax(pc.grouping, u.grouping);

                        sql = "update PC_tb set download=1,maxStep=@max, grouping=@grouping where pc_id=@pcid";
                        sc = new SQLCommand(sql);
                        sc.Add("@max", pc.maxStep);
                        sc.Add("@grouping", pc.grouping);
                        sc.Add("@pcid", pc.pc_id);
                        int rtn = Convert.ToInt32(sc.ExecuteNonQuery());
                        if (rtn == 1)
                            return pc;
                    }
                }
                //查看有没有适合的自由任务  
                //sql = "select * from PC_tb where step=@ucode and download=0 and station=0 and PC_tb.PLID=@plid and (PC_tb.grouping=0 or @ugroup=0 or PC_tb.grouping=@ugroup)";
                sql = "select PC_tb.* from PC_tb join Order_tb on pc_id=id where (step=@ucode or step=@ucode2 or step=@ucode3) and download=0 and station=0 and PC_tb.PLID=@plid and (PC_tb.grouping=0 or @ugroup=0 or PC_tb.grouping=@ugroup) order by Order_tb.rank desc,Order_tb.finish_time asc";

                sc = new SQLCommand(sql);
                sc.Add("@loginid", u.login_id);
                sc.Add("@ucode", u.code== 35 ? 0 : u.code); //申请特体以外的打版任务 
                sc.Add("@ucode2", u.code2 == 35 ? 0 : u.code2);
                sc.Add("@ucode3", u.code3 == 35 ? 0 : u.code3);
                sc.Add("@plid", u.PLID);
                sc.Add("@ugroup", u.grouping);
                dt = sc.ExecuteScalars();
                if (dt != null)
                {
                    List<PC> pcList = DataTableToList<PC>(dt);
                    foreach (PC pc in pcList)
                    {
                        pc.maxStep = GetMax(pc.maxStep, pc.step);
                        pc.grouping = GetMax(pc.grouping, u.grouping);

                        sql = "update PC_tb set download=1,station=@loginid,maxStep=@max, grouping=@grouping where station=0 and pc_id=@pcid";
                        sc = new SQLCommand(sql);
                        sc.Add("@loginid", u.login_id);
                        sc.Add("@max", pc.maxStep);
                        sc.Add("@grouping", pc.grouping);
                        sc.Add("@pcid", pc.pc_id);

                        int rtn = Convert.ToInt32(sc.ExecuteNonQuery());
                        if (rtn == 1)
                            return pc;
                    }
                }
                //不能为用户找到合适的任务，并不是件大事，因为本来就有没事做的可能 
                return null;
            }
            catch (Exception e)
            {
                WriteLog("LockTask", e.Message);
                return null;
            }
        }

        /// <summary>
        /// 检查和pc邦定的生产单,是否工序相同 
        /// </summary>  
        /// <param name="u"></param>
        /// <returns></returns>
        protected bool StepSame(PC pc)
        {
            if (pc.bind_id == 0)
                return true;

            SQLCommand sc = new SQLCommand("select count(*) from PC_tb where bind_id=@bindid", "@bindid", pc.pc_id);
            int a = int.Parse(sc.ExecuteScalar());

            WriteDebug("StepSame a = ", a.ToString());

            sc = new SQLCommand("select count(*) from PC_tb where bind_id=@bindid and step=@pcstep");
            sc.Add("@bindid", pc.pc_id);
            sc.Add("@pcstep", pc.step);
            int b = int.Parse(sc.ExecuteScalar());

            WriteDebug("StepSame b = ", b.ToString());

            return a == b;
        }

        /// <summary>
        /// 获得一个流程，分给他  
        /// </summary>  
        /// <param name="u"></param>
        /// <returns></returns>
        protected PC LockBed(User u)
        {
            string sql = "";
            SQLCommand sc = null;
            try
            {
                //sql = "select PC_tb.* from PC_tb where station=@loginid and download=0";
                sql = "select PC_tb.* from PC_tb join Order_tb on pc_id=id where station=@loginid and download=0 order by Order_tb.rank desc,Order_tb.finish_time desc";
                sc = new SQLCommand(sql, "@loginid", u.login_id);
                DataTable dt = sc.ExecuteScalars();
                if (dt != null)
                {
                    List<PC> pcList = DataTableToList<PC>(dt);
                    WriteDebug("LockBed 预分配 = ", pcList.Count.ToString());
                    foreach (PC pc in pcList)
                    {
                        if (StepSame(pc))
                        {
                            pc.maxStep = GetMax(pc.maxStep, pc.step);
                            sql = "update PC_tb set download=1,maxStep=@max where pc_id=@pcid";
                            sc = new SQLCommand(sql);
                            sc.Add("@max", pc.maxStep);
                            sc.Add("@pcid", pc.pc_id);
                            int rtn = Convert.ToInt32(sc.ExecuteNonQuery());
                            if (rtn == 1)
                                return pc;

                        }
                    }
                }


                //查看有没有适合的自由任务  
                //多个生产单邦定的话, 其中有一个是主生产单,其bind_id = id,其他生产单的bind_id = 主生产单的id
                //sql = "select * from PC_tb where step=@ucode and download=0 and station=0 and PC_tb.PLID=@plid and (PC_tb.grouping=0 or @ugroup=0 or PC_tb.grouping=@ugroup) and (bind_id=0 or bind_id=pc_id)";

                sql = "select PC_tb.* from PC_tb join Order_tb on pc_id=id where (step=@ucode or step=@ucode2 or step=@ucode3) and download=0 and station=0 and PC_tb.PLID=@plid and (PC_tb.grouping=0 or @ugroup=0 or PC_tb.grouping=@ugroup) and (Order_tb.bind_id=0 or Order_tb.bind_id=pc_id) order by Order_tb.rank desc,Order_tb.finish_time desc";

                sc = new SQLCommand(sql);
                sc.Add("@loginid", u.login_id);
                sc.Add("@ucode", u.code);
                sc.Add("@ucode2", u.code2);
                sc.Add("@ucode3", u.code3);
                sc.Add("@plid", u.PLID);
                sc.Add("@ugroup", u.grouping);
                dt = sc.ExecuteScalars();
                if (dt != null)
                {
                    List<PC> pcList = DataTableToList<PC>(dt);
                    WriteDebug("LockBed 自由任务 = ", pcList.Count.ToString());
                    foreach (PC pc in pcList)
                    {
                        if (StepSame(pc))
                        {
                            pc.maxStep = GetMax(pc.maxStep, pc.step);
                            sql = "update PC_tb set download=1,station=@loginid,maxStep=@max where station=0 and pc_id=@pcid";
                            sc = new SQLCommand(sql);
                            sc.Add("@loginid", u.login_id);
                            sc.Add("@max", pc.maxStep);
                            sc.Add("@pcid", pc.pc_id);
                            int rtn = Convert.ToInt32(sc.ExecuteNonQuery());
                            if (rtn == 1)
                                return pc;
                        }
                    }

                }


                //不能为用户找到合适的任务，并不是件大事，因为本来就有没事做的可能 
                return null;
            }
            catch (Exception e)
            {
                WriteLog("LockBed", e.Message);
                return null;
            }
        }

        #region 检查是否有这个流程
        /// <summary>
        /// 检查是否有适当的任务
        /// </summary>
        /// <param name="u"></param>
        /// <param name="isOrder"></param>
        /// <returns>0没有  1有流程</returns>
        protected int CheckIsHavePC(User u)
        {
            try
            {
                string sql = "";
                SQLCommand sc = null;
                int rtn = 0;
                #region 自由任务
                sql = "select count(pc_id) from PC_tb where (step=@ucode or step=@ucode2 or step=@ucode3) and maxStep<step and download=0 and station=0 and PC_tb.PLID=@plid and (PC_tb.grouping=0 or @ugroup=0 or PC_tb.grouping=@ugroup)";

                sc = new SQLCommand(sql);
                sc.Add("@ucode", u.code);
                sc.Add("@ucode2", u.code2);
                sc.Add("@ucode3", u.code3);
                sc.Add("@loginid", u.login_id);
                sc.Add("@plid", u.PLID);
                sc.Add("@ugroup", u.grouping);
                rtn += Convert.ToInt32(sc.ExecuteScalar());
                

                #endregion
                #region  预分配任务
                sql = "select count(pc_id) from PC_tb where station=@loginid and download=0";
                sc = new SQLCommand(sql, "@loginid", u.login_id);
                #endregion
                rtn += Convert.ToInt32(sc.ExecuteScalar());
                return rtn;
            }
            catch (Exception ex)
            {
                WriteDebug("CheckIsHavePC", "异常:"+ex.Message);
                return 0;
            }
            
        }

        #endregion

    }
}
